package com.atguigu.system.controller;

import com.atguigu.model.system.SysUser;
import com.atguigu.model.vo.LoginVo;
import com.atguigu.system.common.result.Result;
import com.atguigu.system.common.utils.JwtHelper;
import com.atguigu.system.common.utils.MD5;
import com.atguigu.system.exception.CustomerException;
import com.atguigu.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "后台登录管理")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {
    @Autowired
    private SysUserService sysUserService;

    //login
    @ApiOperation(value = "登录接口")
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo){

        SysUser sysUser = sysUserService.getByName(loginVo.getUsername());
        //登录判断
        if (sysUser == null){
            throw new CustomerException(214,"账号输入不正确!");
        }

        if (!MD5.encrypt(loginVo.getPassword()).equals(sysUser.getPassword()))
        {
            throw new CustomerException(215,"密码输入不正确!");
        }

        if (sysUser.getStatus() == 0){
            throw new CustomerException(217,"账号已被禁用，请练习客服");
        }

        //用户信息封装token
        String userId = sysUser.getId();
        String username = sysUser.getUsername();
        String JwtToken = JwtHelper.createToken(userId, username);

        //用map返回token键值对
        Map<String, Object> map = new HashMap<>();
        map.put("token",JwtToken);
        return Result.ok(map);
    }

    //info
    @ApiOperation(value = "展示用户信息接口")
    @GetMapping("/info")
    public Result info(HttpServletRequest request){
        //从请求头获取token
        String token = request.getHeader("token");

        //从token中获取用户名
        String username = JwtHelper.getUsername(token);

        //根据用户名，查询用户基本信息、权限信息
        Map<String, Object> map = sysUserService.getInfo(username);

        //返回map键值对
        return Result.ok(map);
    }
}
